package com.example.sunsg.okhttptest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.alibaba.fastjson.annotation.JSONField;
import com.breadtrip.R;
import com.example.sunsg.okhttptest.Manager.FrescoManager;
import com.example.sunsg.okhttptest.http.OkHttpManager;
import com.example.sunsg.okhttptest.util.DisplayUtils;
import com.example.sunsg.okhttptest.util.GsonUtil;
import com.example.sunsg.okhttptest.util.Util;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.annotations.SerializedName;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FrescoImageActivity extends ActionBarActivity {
    private ListView mListView;
    private LayoutInflater mInflater;
    private Handler mHandler = new Handler();
    private MyAdapter mMyAdapter;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fresco_image);
        mListView = (ListView) findViewById(R.id.listview);
        mMyAdapter = new MyAdapter(getApplicationContext());
        mListView.setAdapter(mMyAdapter);// 2387721676
        String url = "http://api.breadtrip.com/v2/new_trip/spot/?spot_id=2387722154";
//        OkHttpManager.get(url).builder().enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String result = response.body().string();
//                    Log.i("test", "result = " + result);
//                    final Responses res = (Responses) GsonUtil.fromJson(result, Responses.class);
//                    mHandler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (res != null) {
//                                mMyAdapter.setItem(res.data.getSpot().getList());
//                            }
//                        }
//                    });
//
//                }
//            }
//        });
        OkHttpManager.get(url).classs(Responses.class).builder().enqueue2(new OkHttpManager.CallBack<Responses>() {
            @Override
            public void onSuccess(final Response response, final Responses resultObject) throws IOException {
                String result = response.body().string();
                Log.i("test", "result = " + result);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (resultObject != null) {
                            mMyAdapter.setItem(resultObject.data.getSpot().getList());
                        }
                    }
                });
            }

            @Override
            public void onFaile(Request request, IOException e) {

            }
        });

//        OkHttpManager.enqueue("http://api.breadtrip.com/v2/new_trip/spot/?spot_id=2387722154", new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String result = response.body().string();
//                    Log.i("test", "result = " + result);
//                    final Responses res = (Responses) GsonUtil.fromJson(result, Responses.class);
//                    mHandler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (res != null) {
//                                mMyAdapter.setItem(res.data.getSpot().getList());
//                            }
//                        }
//                    });
//
//                }
//            }
//        });
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "FrescoImage Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.example.sunsg.okhttptest/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "FrescoImage Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.example.sunsg.okhttptest/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }

    private class MyAdapter extends BaseAdapter {
        private List<ImageData> mItem;
        private int displayWidth;
        private Context mContext;

        public MyAdapter(Context context) {
            mContext = context;
            mInflater = LayoutInflater.from(context);
            mItem = new ArrayList<ImageData>();
            displayWidth = DisplayUtils.getScreenWidth(context) - Util.dp2px(context, 20);
        }

        public void setItem(List<ImageData> item) {
            this.mItem = item;
            notifyDataSetChanged();
        }


        @Override
        public int getCount() {
            return mItem.size();
        }

        @Override
        public ImageData getItem(int position) {
            return mItem.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.fresco_image_activity_item, parent, false);
                holder = new ViewHolder();
                holder.imageView = (SimpleDraweeView) convertView.findViewById(R.id.ivCover);
                holder.progressBar = ((ProgressBar) convertView.findViewById(R.id.progressBar));
                holder.progressBar.setMax(10000);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            ImageData data = getItem(position);
            float showHeitht = displayWidth * data.getHeight() / (float) data.getWidth();
            holder.imageView.getLayoutParams().width = displayWidth;
            holder.imageView.getLayoutParams().height = (int) showHeitht;
            FrescoManager.loadUrl(data.getUrl())
                    .placeImageHolder(R.drawable.img_create_trip_default_cover)
                    .autoRotate(true)
                    .resize(displayWidth, (int) showHeitht)
                    .controllerListener(new BaseControllerListener() {
                        @Override
                        public void onFinalImageSet(String id, Object imageInfo, Animatable animatable) {
                            super.onFinalImageSet(id, imageInfo, animatable);
//                            Log.i("test", "image success " + id);
                        }
                    })
                    .progressBarDrawable(new SimpleProgressDrawable() {
                        @Override
                        protected boolean onLevelChange(int level) {
                            Log.i("test", position + " level = " + level);
                            holder.progressBar.setProgress(level);
                            return super.onLevelChange(level);
                        }
                    })
                    .builder()
                    .into(holder.imageView);
            if (position == 0) {
                convertView.setPadding(0, Util.dp2px(mContext, 20), 0, 0);
            } else if (position == getCount() - 1) {
                convertView.setPadding(0, 0, 0, Util.dp2px(mContext, 20));
            } else {
                convertView.setPadding(0, 0, 0, 0);
            }
            return convertView;
        }

        class ViewHolder {
            SimpleDraweeView imageView;
            ProgressBar progressBar;
        }

    }

    private class SimpleProgressDrawable extends Drawable {
        @Override
        public void draw(Canvas canvas) {

        }

        @Override
        public void setAlpha(int alpha) {

        }

        @Override
        public void setColorFilter(ColorFilter cf) {

        }

        @Override
        public int getOpacity() {
            return 0;
        }

        @Override
        protected boolean onLevelChange(int level) {
            return super.onLevelChange(level);
        }
    }


    private class ImageData {
        @SerializedName("photo_width")
//        @JSONField(name = "photo_width")
        private int width;
        @SerializedName("photo_height")
//        @JSONField(name = "photo_height")
        private int height;
        @SerializedName("photo")
//        @JSONField(name = "photo")
        private String url;

        public ImageData() {
        }

        public ImageData(int width, int height, String url) {
            this.width = width;
            this.height = height;
            this.url = url;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }

    private class Spot {
        @SerializedName("detail_list")
//        @JSONField(name = "detail_list")
        private List<ImageData> list;

        public Spot() {
        }

        public List<ImageData> getList() {
            return list;
        }

        public void setList(List<ImageData> list) {
            this.list = list;
        }
    }

    private class Data {
        private Spot spot;

        public Data() {
        }

        public Spot getSpot() {
            return spot;
        }

        public void setSpot(Spot spot) {
            this.spot = spot;
        }

    }

    private class Responses {
        private Data data;
        private int status;
        private String message;

        public Responses() {
        }

        public Data getData() {
            return data;
        }

        public void setData(Data data) {
            this.data = data;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

}
